import React, { useState, useRef, useEffect } from 'react';
import { Button, Popconfirm, Checkbox, Upload, FormInstance, message, Tooltip } from 'antd';
import { PageContainer } from '@ant-design/pro-layout';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { getShopOrderList, doDelivery, updateOrderStatus, downloadOrder } from '@/services/shop/api';
import OptForm from './OptForm';
import { MsgType, showMsg, formatDate, currentDate, getCache, setCache, parseDate, isNull, isSupportSticky } from '@/utils/utils';
import { history } from 'umi';
// @ts-ignore
import Cookies from 'js-cookie';
import BreadcrumbDept from '@/components/BreadcrumbDept';
import PermissionControl from '@/components/PermissionControl';
import { DownloadOutlined } from '@ant-design/icons';
import TakeDialog from './TakeDialog';
import { imgPrefix } from '@/utils/constants';
import './style.less';
interface IndexProps {
  location?: any;
}

const Index: React.FC<IndexProps> = (props) => {
  const { location } = props;
  const { query } = location;

  // 批量发货单
  const downloadAddr = `${imgPrefix}xlsx/批量发货单.xlsx`;
  console.log('downloadAddr', downloadAddr)

  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [currentRow, setCurrentRow] = useState<SHOPAPI.ShopOrder>({} as SHOPAPI.ShopOrder);
  const actionRef = useRef<ActionType>();
  const formRef = useRef<FormInstance>();
  const [checkVals, setCheckVals] = useState<string[]>();
  const [exportFlag, setExportFlag] = useState<boolean>(false);
  const [loading, setLoading] = useState<boolean>(false);
  const [searchParams, setSearchParams] = useState({});
  const [showTakeId, setShowTakeId] = useState(''); // 确认提货弹窗

  const columns: ProColumns<SHOPAPI.ShopOrder>[] = [
    {
      title: '订单编号',
      dataIndex: 'order_id',
      width: 130,
      fieldProps: {
        placeholder: '输入订单编号',
      }
    },
    {
      title: '提交时间',
      dataIndex: 'create_date',
      valueType: 'date',
      width: 130,
      render: (dom, entity) => {
        return `${entity.create_date} ${entity.create_time}`
      }
    },
    {
      title: '用户账号',
      dataIndex: 'user_name',
      width: 150,
      search: false
    },
    {
      title: '订单金额',
      dataIndex: 'order_price',
      valueType: 'money',
      align: 'right',
      width: 70,
      search: false
    },
    {
      title: '快递费',
      dataIndex: 'mail_price',
      valueType: 'money',
      align: 'right',
      width: 70,
      search: false
    },
    {
      title: '支付金额',
      dataIndex: 'pay_price',
      align: 'right',
      search: false,
      width: 70,
      valueType: 'money',
      render: (val, record) => {
        return ['T', 'C'].includes(record.order_status) ? '￥0.00' : `￥${record.pay_price}`;
      }
    },
    {
      title: '配送方式',
      dataIndex: 'ship_method',
      valueType: 'select',
      width: 60,
      valueEnum: {
        K: '快递',
        Z: '自提'
      }
    },
    {
      title: '收货人',
      hideInTable: true,
      dataIndex: 'receiver',
      fieldProps: {
        placeholder: '收货人姓名/手机号码',
      }
    },
    {
      title: '订单状态',
      dataIndex: 'order_status',
      valueType: 'select',
      width: 80,
      search: false,
      render: (dom, entity) => {
        if (entity.ship_method === 'Z') {
          return {
            T: '待付款',
            P: '待自提',
            S: '待自提',
            F: '已完成',
            C: '已关闭',
            R: '已退款',
            G: '已退货',
          }[entity.order_status]
        }

        return {
          T: '待付款',
          P: '待发货',
          S: '已发货',
          F: '已完成',
          C: '已关闭',
          R: '已退款',
          G: '已退货',
        }[entity.order_status]
      }
    },
    {
      title: '订单状态',
      dataIndex: 'order_status',
      valueType: 'select',
      hideInTable: true,
      width: 80,
      valueEnum: {
        T: '待付款',
        P: '待发货',
        S: '已发货',
        F: '已完成',
        R: '已退款',
        G: '已退货',
        C: '已关闭'
      }
    },
    {
      title: '售后记录',
      hideInSearch: true,
      width: 80,
      render: (dom, entity) => {
        return !entity.apply_count ? '-' : <a onClick={() => {
          history.push({
            pathname: '/shop/after-sale',
            query: {
              order_id: entity.order_id
            }
          })
        }}>{entity.apply_count}笔</a>;
      }
    },
    {
      title: '搜索结果不包括',
      dataIndex: 'not_order_status_list',
      hideInTable: true,
      renderFormItem: (_, { type, defaultRender, ...rest }, form) => {
        if (type === 'form') {
          return null
        }
        return (
          <Checkbox.Group
            value={checkVals}
            onChange={setCheckVals}
            options={
              [
                {
                  label: '已完成',
                  value: 'F'
                },
                {
                  label: '已关闭',
                  value: 'C'
                }
              ]
            }
          />
        );
      }
    },
    {
      title: '操作',
      align: 'center',
      // fixed: 'right',
      fixed: isSupportSticky() ? 'right' : '',
      width: 120,
      valueType: 'option',
      render: (_, record) => {
        // 订单状态 T：待付款，P：待发货，S：已发货，F：已完成，C：已关闭 ,
        const { order_status, ship_method } = record;

        if (['P'].includes(order_status)) {
          return [
            <PermissionControl key="view" action_id="600604003">
              <a onClick={() => {
                history.push({
                  pathname: '/shop/order/detail',
                  query: {
                    order_id: record.order_id
                  }
                })
              }}>查看</a>
            </PermissionControl>,
              
            ship_method === 'K' && <PermissionControl action_id="600604004">
              <a key="delivery" onClick={() => {
                setCurrentRow(record);
                handleModalVisible(true);
              }}>订单发货</a>
            </PermissionControl>
          ]
        }

        if (['S'].includes(order_status)) {
          return [
            <PermissionControl key="view" action_id="600604003">
              <a onClick={() => {
                history.push({
                  pathname: '/shop/order/detail',
                  query: {
                    order_id: record.order_id
                  }
                })
              }}>查看</a>
            </PermissionControl>,
            ship_method === 'Z' && <PermissionControl action_id="600604005">
              <a onClick={() => setShowTakeId(record.order_id)}>确认提货</a>
            </PermissionControl> 
          ]
        }

        if (!['C'].includes(order_status)) {
          return [
            <a key="view" onClick={() => {
              history.push({
                pathname: '/shop/order/detail',
                query: {
                  order_id: record.order_id
                }
              })
            }}>查看</a>
          ]
        }
        return []
      }
    }
  ];

  const handleAdd = async (data: any) => {
    try {
      await doDelivery(data);
      showMsg('已发货', MsgType.SUCCESS);
      return true
    } catch (error) {
      showMsg(error?.data?.errmsg)
      return false
    }
  }

  useEffect(() => {
    if (query?.from !== 'detail') {
      setCache('shop_order', '');
      formRef.current?.setFieldsValue({
        create_date: query.order_status ? null : currentDate(),
        order_status: query.order_status || null
      });
      setCheckVals(['F', 'C']);
      formRef.current?.submit();
      return
    }
    let searchCondition = getCache('shop_order');
    searchCondition = JSON.parse(searchCondition || '{}');

    formRef.current?.setFieldsValue({
      create_date: searchCondition.create_date ? parseDate(searchCondition.create_date) : currentDate(),
      order_id: searchCondition.order_id,
      ship_method: searchCondition.ship_method,
      receiver: searchCondition.receiver
    });
    setCheckVals(searchCondition.not_order_status_list ? searchCondition.not_order_status_list : ['F', 'C']);
    formRef.current?.submit();
  }, [])

  const download = async() => {
    setLoading(true);
    await downloadOrder(searchParams).then(res => {
      setLoading(false);
      window.open(`/api/report/${res.file_token}/down`);
    }).catch(res => {
      setLoading(false);
    });
  }

  // @ts-ignore
  const onUploadChange = ({file, fileList}) => {
    if (file.status === 'uploading') {
      setLoading(true);
    } else if (file.status === 'done') {
      setLoading(false);
      message.success(`${file.name} 导入成功`);
      actionRef.current?.reload();
    } else if (file.status === 'error') {
      setLoading(false);
      showMsg(file.response.errmsg);
    }
  }

  return (
    <PageContainer extra={[
      <BreadcrumbDept />
     ]} breadcrumb={{}}>
      <ProTable<SHOPAPI.ShopOrder, SHOPAPI.ShopOrder & COMMON.PageParams>
        actionRef={actionRef}
        bordered
        formRef={formRef}
        manualRequest={true}
        rowKey="order_id"
        search={{
          span: 6,
          labelWidth: 110,
          collapsed: false,
          collapseRender: () => '',
          optionRender: (searchConfig, formProps, dom) => {
            dom.shift();
            return [
              <PermissionControl key="search" action_id="600604000">{dom}</PermissionControl>,
              <PermissionControl key="export" action_id="600604001">
                <Button loading={loading} disabled={exportFlag} type="primary" onClick={download}>导出订单</Button>
              </PermissionControl>
            ];
          }
        }}
        request={async (params) => {
          try {
            if (params.create_date) {
              params.create_date = formatDate(params.create_date, 'YYYYMMDD')
            }
            if (checkVals?.length) {
              // @ts-ignore
              params.not_order_status_list = checkVals;
            }
            
            const searchCondition = {}
            for (const prop in params) {
              if (!['current', 'pageSize'].includes(prop)) {
                searchCondition[prop] = params[prop];
              }
            }
            setCache('shop_order', JSON.stringify(searchCondition));
            setSearchParams(params);
            const data: SHOPAPI.ShopOrderList = await getShopOrderList(params);
            setExportFlag(data.record_list.length <= 0);
            return {
              data: data.record_list,
              success: true,
              total: data.sum_record_num
            };
          } catch (error) {
            showMsg(error?.data?.errmsg);
            return {
              data: [],
              success: true,
              total: 0
            };
          }
        }}
        columns={columns}
        options={false}
        toolbar={{
          menu: {
            type: 'inline',
            items: [
              {
                key: 'import',
                label: <PermissionControl action_id="600604002">
                <Upload 
                  disabled={loading} 
                  name="file" 
                  action="/api/shop/order/upload" 
                  onChange={onUploadChange} 
                  showUploadList={false} 
                  beforeUpload={() => message.loading('请稍后', 2)}
                  headers={{'Oper-Token': localStorage.getItem('Oper-Token'), 'Action_Id': '600604002'}}
                >
                  <span style={{ padding: '3px 8px', background: '#096dd9', fontSize: 12, color: '#fff', display: 'inline-block', borderRadius: '3px', cursor: 'pointer' }}>
                    批量导入发货单
                    <Tooltip
                      placement="bottomRight"
                      title={
                        <a
                          href={downloadAddr}
                          target="_blank"
                          style={{ color: '#fff' }}
                          onClick={e => e.stopPropagation()}
                        >
                          下载模版
                        </a>
                      }
                    >
                      <DownloadOutlined style={{ marginLeft: 10 }} />
                    </Tooltip>
                  </span>
                </Upload>
                </PermissionControl>
              }
            ]
          }
        }}
        pagination={{
          showQuickJumper: true
        }}
      />

      {
        createModalVisible && <OptForm 
        actionRef={actionRef} 
        handleAdd={handleAdd} 
        handleModalVisible={handleModalVisible} 
        currentRow={currentRow} />
      }
      {
        !isNull(showTakeId) &&
        <TakeDialog
          id={showTakeId}
          onSubmit={e => {
            setShowTakeId('');
            actionRef.current?.reload();
          }}
          onCancel={() => {
            setShowTakeId('');
          }}
        />
      }
      
    </PageContainer>
  );
};

export default Index;
